"""

"""

from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.textinput import TextInput
from kivy.uix.tabbedpanel import TabbedPanel, TabbedPanelItem
from kivy.uix.popup import Popup
from kivy.uix.filechooser import FileChooserListView
from kivy.core.clipboard import Clipboard
from pathlib import Path
import os

from src.core.output_formatter import OutputFormatter

class ResultViewer(BoxLayout):
    """"""
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.spacing = 10
        self.padding = 20
        
        self.result_data = None
        self._build_ui()
    
    def _build_ui(self):
        """"""
        # 
        title = Label(
            text=" Processing Results",
            font_size=40,
            size_hint_y=None,
            height=70,
            bold=True,
            color=(0.2, 0.6, 0.9, 1)
        )
        self.add_widget(title)
        
        # 
        self.tab_panel = TabbedPanel(
            do_default_tab=False,
            tab_width=120
        )
        
        # 
        self.summary_tab = TabbedPanelItem(text=' Summary')
        self.summary_tab.add_widget(self._create_summary_content())
        self.tab_panel.add_widget(self.summary_tab)
        
        # 
        self.keywords_tab = TabbedPanelItem(text=' Keywords')
        self.keywords_tab.add_widget(self._create_keywords_content())
        self.tab_panel.add_widget(self.keywords_tab)
        
        # 
        self.chapters_tab = TabbedPanelItem(text=' Chapters')
        self.chapters_tab.add_widget(self._create_chapters_content())
        self.tab_panel.add_widget(self.chapters_tab)
        
        # 
        self.transcript_tab = TabbedPanelItem(text=' Transcript')
        self.transcript_tab.add_widget(self._create_transcript_content())
        self.tab_panel.add_widget(self.transcript_tab)
        
        self.add_widget(self.tab_panel)
        
        # 
        button_layout = BoxLayout(
            orientation='horizontal',
            size_hint_y=None,
            height=50,
            spacing=10
        )
        
        # 
        export_btn = Button(text="Export All", font_size=24, height=60)  # 放大字体
        export_btn.bind(on_press=self._export_result)
        button_layout.add_widget(export_btn)
        
        # 
        save_btn = Button(text="Save Current View", font_size=24, height=60)  # 放大字体
        save_btn.bind(on_press=self._save_to_file)
        button_layout.add_widget(save_btn)
        
        # 
        copy_btn = Button(text="Copy Current View", font_size=24, height=60)  # 放大字体
        copy_btn.bind(on_press=self._copy_to_clipboard)
        button_layout.add_widget(copy_btn)
        
        self.add_widget(button_layout)

    # ... (Content creation methods remain the same) ...
    def _create_summary_content(self):
        """"""
        layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
        self.stats_label = Label(text="Statistics will be displayed here...", size_hint_y=None, height=80, font_size=24)
        layout.add_widget(self.stats_label)
        scroll = ScrollView()
        self.summary_text = TextInput(text="AI-generated summary will be displayed here...", multiline=True, readonly=True, font_size=28)
        scroll.add_widget(self.summary_text)
        layout.add_widget(scroll)
        return layout

    def _create_keywords_content(self):
        """"""
        layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
        keywords_title = Label(text="Extracted Keywords", size_hint_y=None, height=60, font_size=32)
        layout.add_widget(keywords_title)
        scroll = ScrollView()
        self.keywords_text = TextInput(text="Extracted keywords will be displayed here...", multiline=True, readonly=True, font_size=28)
        scroll.add_widget(self.keywords_text)
        layout.add_widget(scroll)
        return layout

    def _create_chapters_content(self):
        """"""
        layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
        chapters_title = Label(text="Chapter Segments", size_hint_y=None, height=60, font_size=32)
        layout.add_widget(chapters_title)
        scroll = ScrollView()
        self.chapters_text = TextInput(text="Identified chapters will be displayed here...", multiline=True, readonly=True, font_size=28)
        scroll.add_widget(self.chapters_text)
        layout.add_widget(scroll)
        return layout

    def _create_transcript_content(self):
        """"""
        layout = BoxLayout(orientation='vertical', spacing=10, padding=10)
        transcript_title = Label(text="Full Transcript Text", size_hint_y=None, height=60, font_size=32)
        layout.add_widget(transcript_title)
        scroll = ScrollView()
        self.transcript_text = TextInput(text="Transcript text will be displayed here...", multiline=True, readonly=True, font_size=28)  # 放大两倍字体
        scroll.add_widget(self.transcript_text)
        layout.add_widget(scroll)
        return layout

    def update_result(self, result_data):
        """"""
        self.result_data = result_data
        if not result_data: return
        transcript = result_data.get('transcript', {})
        summary = result_data.get('summary', {})
        stats_text = f"""
Processing Statistics:
• Original text length: {len(transcript.get('text', ''))} characters
• Summary length: {len(summary.get('summary', ''))} characters
• Detected language: {transcript.get('language', 'Unknown')}
• Processing time: {result_data.get('processing_time', 'Unknown')} """.strip()
        self.stats_label.text = stats_text
        if 'summary' in summary: self.summary_text.text = summary['summary']
        keywords = summary.get('keywords', [])
        if keywords: self.keywords_text.text = " Keywords:\n\n" + "\n".join([f"• {kw}" for kw in keywords])
        chapters = summary.get('chapters', [])
        if chapters:
            chapters_text = " Chapter Segments:\n\n"
            for i, chapter in enumerate(chapters, 1):
                chapters_text += f"Chapter {i}: {chapter.get('title', 'Unknown')}\nTime: {chapter.get('start_time', 0):.1f}s - {chapter.get('end_time', 0):.1f}s\nContent: {chapter.get('content', '')[:100]}...\n\n"
            self.chapters_text.text = chapters_text
        if 'text' in transcript: self.transcript_text.text = transcript['text']

    def _get_current_tab_content(self):
        current_tab = self.tab_panel.current_tab
        if current_tab == self.summary_tab:
            return self.summary_text.text
        elif current_tab == self.keywords_tab:
            return self.keywords_text.text
        elif current_tab == self.chapters_tab:
            return self.chapters_text.text
        elif current_tab == self.transcript_tab:
            return self.transcript_text.text
        return ""

    def _show_popup(self, title, content):
        popup = Popup(title=title, content=content, size_hint=(0.9, 0.9))
        content.bind(on_success=lambda instance, path, selection: popup.dismiss(),
                     on_cancel=lambda instance: popup.dismiss())
        popup.open()

    def _export_result(self, instance):
        """"""
        if not self.result_data: return
        
        content = BoxLayout(orientation='vertical')
        file_chooser = FileChooserListView(dirselect=True)
        content.add_widget(file_chooser)
        
        btn_layout = BoxLayout(size_hint_y=None, height=50)
        save_btn = Button(text="Select This Directory")
        def select_dir(instance):
            if file_chooser.path:
                try:
                    formatter = OutputFormatter()
                    base_path = os.path.join(file_chooser.path, Path(self.result_data['video_info']['file_path']).stem)
                    formatter.save_multiple_formats(self.result_data, base_path, formats=['md', 'html', 'json', 'srt', 'txt'])
                    self._show_simple_popup("Export Success", f"All formats have been exported to:\n{file_chooser.path}")
                except Exception as e:
                    self._show_simple_popup("Export Failed", str(e))
            popup.dismiss()
        save_btn.bind(on_press=select_dir)
        btn_layout.add_widget(save_btn)
        
        cancel_btn = Button(text="Cancel")
        def dismiss_popup(instance):
            popup.dismiss()
        cancel_btn.bind(on_press=dismiss_popup)
        btn_layout.add_widget(cancel_btn)
        content.add_widget(btn_layout)

        popup = Popup(title="Select Export Directory", content=content, size_hint=(0.9, 0.9))
        popup.open()

    def _save_to_file(self, instance):
        """"""
        content_to_save = self._get_current_tab_content()
        if not content_to_save: return

        content = BoxLayout(orientation='vertical')
        file_chooser = FileChooserListView()
        file_chooser.text_input = TextInput(text="output.txt", multiline=False, size_hint_y=None, height=40)
        content.add_widget(file_chooser)
        content.add_widget(file_chooser.text_input)

        btn_layout = BoxLayout(size_hint_y=None, height=50)
        save_btn = Button(text="Save")
        def save_file(instance):
            try:
                file_path = os.path.join(file_chooser.path, file_chooser.text_input.text)
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content_to_save)
                self._show_simple_popup("Save Success", f"File has been saved to:\n{file_path}")
            except Exception as e:
                self._show_simple_popup("Save Failed", str(e))
            popup.dismiss()
        save_btn.bind(on_press=save_file)
        btn_layout.add_widget(save_btn)

        cancel_btn = Button(text="Cancel")
        def dismiss_popup(instance):
            popup.dismiss()
        cancel_btn.bind(on_press=dismiss_popup)
        btn_layout.add_widget(cancel_btn)
        content.add_widget(btn_layout)

        popup = Popup(title="Save Current View", content=content, size_hint=(0.9, 0.9))
        popup.open()

    def _copy_to_clipboard(self, instance):
        """"""
        content_to_copy = self._get_current_tab_content()
        if content_to_copy:
            Clipboard.copy(content_to_copy)
            self._show_simple_popup("Success", "Current content has been copied to clipboard!")
        else:
            self._show_simple_popup("Notice", "No content to copy.")

    def _show_simple_popup(self, title, message):
        content = BoxLayout(orientation='vertical', spacing=10, padding=10)
        content.add_widget(Label(text=message))
        ok_btn = Button(text="OK", size_hint_y=None, height=50)
        content.add_widget(ok_btn)
        popup = Popup(title=title, content=content, size_hint=(0.6, 0.4))
        ok_btn.bind(on_press=popup.dismiss)
        popup.open()

    def clear_result(self):
        """"""
        self.result_data = None
        self.stats_label.text = "Statistics will be displayed here..."
        self.summary_text.text = "AI-generated summary will be displayed here..."
        self.keywords_text.text = "Extracted keywords will be displayed here..."
        self.chapters_text.text = "Chapter information will be displayed here..."
        self.transcript_text.text = "Transcript text will be displayed here..."
